import {defineStore} from 'pinia';
import {ElMessage, ElNotification} from "element-plus";
import {useRouter} from 'vue-router';
import userApi from "api/model/user.js";


export const useUserStore = defineStore('user', {
    state: () => ({
        token: '',
        userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : null,
    }),

    actions: {
        async login(formData) {
            const res = await userApi.login.post(formData);
            const {code, data, msg} = res;
            if (code == 0) {
                ElNotification({
                    title: '登录成功',
                    message: '欢迎回来',
                    type: 'success',
                })
                const {token, userInfo} = data;
                this.token = token;
                this.userInfo = userInfo;
                localStorage.setItem('token', token);
                localStorage.setItem('userInfo', JSON.stringify(userInfo));
            } else {
                ElMessage.warning(msg);
            }
            return res;
        },

        logout(router) {
            localStorage.clear('token');
            localStorage.clear('userInfo');
            this.token = '';
            this.userInfo = null;
            router.push('/login');
        },
    },

})